﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ChessService
{
    public class ServiceChess : IServiceChess
    {
        ChessChallengeEntities dbContext = new ChessChallengeEntities();

        public MoveDetails MakeMove(MoveDetails details)
        {
            string board = LoadGame(details);

            char[,] matrixBoard = GetMatrixFromString(board);

            char figure = matrixBoard[details.StartRow, details.StartColumn];
            matrixBoard[details.StartRow, details.StartColumn] = '-';
            matrixBoard[details.EndRow, details.EndColumn] = figure;

            string upDatedBoard = GetStringFromMatrix(matrixBoard);

            details.GameState = board;

            return details;
        }

        private string GetStringFromMatrix(char[,] matrixBoard)
        {
            StringBuilder result = new StringBuilder();
            for (int row = 0; row < matrixBoard.GetLength(0); row++)
            {
                for (int col = 0; col < matrixBoard.GetLength(1); col++)
                {
                    result.Append(matrixBoard[row, col]);
                }
            }

            return result.ToString();
        }

        private char[,] GetMatrixFromString(string board)
        {
            char[,] result = new char[8, 8];
            int stringIterator = 0;
            for (int row = 0; row < result.GetLength(0); row++)
            {
                for (int col = 0; col < result.GetLength(1); col++)
                {
                    result[row, col] = board[stringIterator];
                    stringIterator++;
                }
            }
            return result;
        }

        private string LoadGame(MoveDetails details)
        {
            if (details.GameID == null)
            {
                int gameID = CreateNewGame();
                details.GameID = gameID;
            }
            string board = GetBoardByID(details.GameID);            
            return board;
        }

        private int CreateNewGame()
        {
            ChessChallengeEntities dbContext = new ChessChallengeEntities();
            Board newBoard = new Board 
            { 
                PlayerA = new Guid(),
                PlayerB = new Guid(), 
                BoardState = "RNBQKBNRPPPPPPPP--------------------------------pppppppprnbqkbnr"
            };
            dbContext.Boards.AddObject(newBoard);
            dbContext.SaveChanges();
            return newBoard.BoardID;
        }

        private string GetBoardByID(int? id)
        {
            string board = dbContext.Boards.FirstOrDefault(b => b.BoardID == id).BoardState;
            return board;
        }
    }
}
